import { createReducer } from 'reduxsauce'
import { REHYDRATE } from 'redux-persist/es/constants'
import {
  SAVE_CONSULTATION_PARAMS,
  UPDATE_CONSULTATION_PARAMS,
  CLEAR_CONSULTATION_PARAMS,
  GET_MY_COUPONS,
  GET_CONSULTATION_AND_RATING,
} from '@ACTIONS/consultation'
import { ADD_COMMENT } from '@ACTIONS/comment'

const INITIAL_STATE = {
  startConsultationData: null,
  couponList: [],
  startTelConsulData: {},
  consulAndRating: {},
  noConsulAndRating: null,
  loadingConsulAndRating: true,
}
const rehydrate = (state, { payload }) => {
  if (payload && payload.consultation) {
    return { ...INITIAL_STATE, ...payload.consultation }
  }
  return { ...state }
}

export default createReducer(INITIAL_STATE, {
  [REHYDRATE]: rehydrate,
  [SAVE_CONSULTATION_PARAMS.REQUEST]: (state, { payload }) => ({
    ...state,
    startConsultationData: payload
  }),
  [UPDATE_CONSULTATION_PARAMS.REQUEST]: (state, { data }) => {
    const { startConsultationData } = state
    if (!data || !startConsultationData) return state
    const { extraData } = startConsultationData
    const newData = { ...startConsultationData, extraData: { ...extraData, ...data }, DoctorId: data.doctorId }
    return {
      ...state,
      startConsultationData: newData
    }
  },
  [CLEAR_CONSULTATION_PARAMS.REQUEST]: state => ({
    ...state,
    startConsultationData: null
  }),

  [GET_MY_COUPONS.SUCCESS]: (state, { data }) => ({
    ...state,
    couponList: data,
  }),

  [GET_CONSULTATION_AND_RATING.REQUEST]: state => ({
    ...state,
    loadingConsulAndRating: true
  }),
  [GET_CONSULTATION_AND_RATING.SUCCESS]: (state, { consulAndRating }) => ({
    ...state,
    consulAndRating,
    loadingConsulAndRating: false,
  }),
  [GET_CONSULTATION_AND_RATING.FAILURE]: (state, { error }) => ({
    ...state,
    noConsulAndRating: error,
  }),
  [ADD_COMMENT.SUCCESS]: (state, { data = {} }) => ({
    ...state,
    consulAndRating: { ...state.consulAndRating, Rating: data }
  }),
})
